package com.nft.service.school.context;

import com.nft.service.school.resp.VerifyCodeResp;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

@Component
public class UserContext {
    public static final String VERIFYCODE_IN_SESSION = "verifycode_in_session";

    public static final String USER_IN_SESSION = "user_in_session";

    /**
     * 反向获取request的方法,请查看RequestContextListener.requestInitialized打包过程
     *
     * @return
     */
    private static HttpSession getSession() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
    }


    public static void putVerifyCode(VerifyCodeResp vc) {
        getSession().setAttribute(VERIFYCODE_IN_SESSION, vc);
    }

    public static void deleteVerifyCode(){
        getSession().removeAttribute(VERIFYCODE_IN_SESSION);
    }

    public static void putUserId(Integer userId) {
        getSession().setAttribute(USER_IN_SESSION, userId);
    }

    public static Integer getCurrentUserId() {
        Integer userId = (Integer) getSession().getAttribute(USER_IN_SESSION);
        return userId;
    }

    public static void deleteCurrentUserId() {
        getSession().removeAttribute(USER_IN_SESSION);
    }

    /**
     * 得到当前的短信验证码
     *
     * @return
     */
    public static VerifyCodeResp getCurrentVerifyCode() {
        VerifyCodeResp verifyCodeResp = (VerifyCodeResp) getSession().getAttribute(VERIFYCODE_IN_SESSION);
        return verifyCodeResp;
    }
}
